//
//  ChatTableViewTextCell.m
//  供销宝
//
//  Created by 金晶 on 17/2/14.
//  Copyright © 2017年 金晶. All rights reserved.
//

#import "ChatTableViewTextCell.h"
#import "LXEmotionManager.h"
#import "UIImage+GIF.h"
#import "UILabel+TapAction.h"
#import "NSString+TimeFormat.h"

@interface ChatTableViewTextCell () <AttributeTapActionDelegate>

@property (nonatomic,strong) ChatMessage *ChatMessage;

@end

@implementation ChatTableViewTextCell


+ (UITableViewCell *)cellWithTableView:(ChatTableView *)tableView messageModel:(ChatMessage *)model withmasTop:(CGFloat)masTop {
    
    static NSString *textCellIndentifier = @"textCellIndentifier";
    
    ChatTableViewTextCell *cell = [tableView dequeueReusableCellWithIdentifier:textCellIndentifier];
    
    if(!cell) {
        
        cell = [[ChatTableViewTextCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:textCellIndentifier];
    }
    
    cell.ChatMessage = model;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if(model.splitTime.length > 0) {
        
        NSString *dateStr = [model.splitTime format];
        
        cell.timeLabel.text = dateStr;//model.messageTime;
        cell.timeLabel.hidden = NO;
    }else {
        cell.timeLabel.hidden =YES;
    }
    
    if(model.msgSourceType==CHAT_MSG_RECV) {
        
        cell.logoImage.frame=CGRectMake(10, masTop, 40, 40);
        
        CGFloat maxWith=kScreenWidth-LEFT_WITH-RIGHT_WITH-14-12-4;
        
        CGRect rect = [cell getContentWidth:maxWith withcontent:[[Common manager] replaceEmoji:model.msgContent]];
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.right+8, masTop, 0, 0);
        }
        
        cell.nickNameLabel.textAlignment = NSTextAlignmentLeft;

        cell.contextBack.frame=CGRectMake(LEFT_WITH, masTop+[cell returnNameTop:isShowNickName], rect.size.width+30, rect.size.height+26);
        cell.contextBack.image=[[UIImage imageNamed:@"wechatback1cover"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        
        cell.textMessageLabel.frame = CGRectMake(cell.contextBack.frame.origin.x+8, cell.contextBack.frame.origin.y+5, cell.contextBack.frame.size.width-16, cell.contextBack.frame.size.height-10);
        cell.textMessageLabel.attributedText= [LXEmotionManager transferMessageString:model.msgContent font:[UIFont systemFontOfSize:16] lineHeight:20];

        [cell.textMessageLabel addAttributeTapActionWithStrings:cell.textMessageLabel.attributedText.string delegate:cell];
        
    }else if (model.msgSourceType==CHAT_MSG_SEND) {
        
        cell.logoImage.frame=CGRectMake(kScreenWidth-10-40, masTop, 40, 40);
        
        BOOL isShowNickName = NO;
        if ([tableView.chatProtocol.chatDelegate respondsToSelector:@selector(isShowNickName)]) {
            isShowNickName = [tableView.chatProtocol.chatDelegate isShowNickName];
        }
        
        if (isShowNickName) {
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 150, [cell returnNameTop:isShowNickName]-3);
        }else{
            cell.nickNameLabel.frame = CGRectMake(cell.logoImage.left-150-8, masTop, 0, 0);
        }
        
        cell.nickNameLabel.textAlignment = NSTextAlignmentRight;
        
        CGFloat maxWith=kScreenWidth-LEFT_WITH-RIGHT_WITH-14-12-4;
        CGRect rect = [cell getContentWidth:maxWith withcontent:[[Common manager] replaceEmoji:model.msgContent]];
        
        cell.contextBack.frame=CGRectMake(kScreenWidth-(rect.size.width+30)-LEFT_WITH, masTop+[cell returnNameTop:isShowNickName], rect.size.width+20, rect.size.height+26);
        cell.contextBack.image=[[UIImage imageNamed:@"wechatback2"] stretchableImageWithLeftCapWidth:10 topCapHeight:25];
        
        cell.textMessageLabel.frame = CGRectMake(cell.contextBack.frame.origin.x+8, cell.contextBack.frame.origin.y+5, cell.contextBack.frame.size.width-16, cell.contextBack.frame.size.height-10);
        cell.textMessageLabel.attributedText= [LXEmotionManager transferMessageString:model.msgContent font:[UIFont systemFontOfSize:16] lineHeight:20];
        
        [cell.textMessageLabel addAttributeTapActionWithStrings:cell.textMessageLabel.attributedText.string delegate:cell];
        
        //正在发送状态
        if(model.messageState ==CHAT_MSG_SENDING){
            [cell.acview startAnimating];
            [cell.acview setHidden:NO];
            [cell.retryButton setHidden:YES];
            
            [cell.acview mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.contextBack.mas_left).offset(-12);
            }];
        }else if (model.messageState ==CHAT_MSG_SEND_NONE) {
            //未发送状态
            [cell.retryButton mas_makeConstraints:^(MASConstraintMaker *make) {
                
                [cell.acview setHidden:YES];
                [cell.retryButton setHidden:NO];
                
                make.centerY.equalTo(cell.contextBack);
                make.right.mas_equalTo(cell.contextBack.mas_left).offset(-12);
            }];
        }else {
            [cell.acview setHidden:YES];
            [cell.retryButton setHidden:YES];
        }
    }

    return cell;
}

//功能待定
- (void)showMenuControllerInView:(ChatTableViewTextCell *)inView
                          bgView:(UIView *)supView {
    
    self.coversImageView.hidden=NO;
    
    [self becomeFirstResponder];

    UIMenuItem *copyTextItem1 = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyTextSender1)];
    UIMenuItem *copyTextItem2 = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(copyTextSender2)];
    
    UIMenuController *menu = [UIMenuController sharedMenuController];
    [menu setTargetRect:supView.frame inView:inView];
    [menu setArrowDirection:UIMenuControllerArrowDefault];
    [menu setMenuItems:@[copyTextItem1,copyTextItem2]];
    
    [menu setMenuVisible:YES animated:YES];
}

#pragma mark 剪切板代理方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    
    if (action == @selector(copyTextSender1)) {
        return true;
    } else  if (action == @selector(copyTextSender2)) {
        return true;
    } else {
        return false;
    }
}

- (void)copyTextSender1 {
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.ChatMessage.msgContent;
}

- (void)copyTextSender2 {
    
    !self.removeChatInfoBlock?:self.removeChatInfoBlock(self.ChatMessage);
}

- (void)copyTextSender3 {
    NSLog(@"333");
}

#pragma mark -
#pragma marl - AttributeTapActionDelegate
- (void)attributeTapReturnString:(NSString *)string range:(NSRange)range index:(NSInteger)index {
    
    NSString *message = [NSString stringWithFormat:@"%@可能是一个电话号码",string];

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleActionSheet];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"呼叫" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *str=[[NSString alloc] initWithFormat:@"tel:%@",string];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"复制" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
        pasteboard.string = string;
    }]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alert animated:YES completion:nil];
    
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
